<?php
/**
 * 脚本
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */
use yii\helpers\Json;
/** @var \yii\web\View $this 视图组件 */
/** @var \builder\menu\MenuBuilder $context 当前组件 */
/** @var string $ajaxRoute Ajax路由 */
/** @var array $rowEvents 行事件 */
/** @var array $behaviorCall 行为调用 */
/** @var boolean $autoRequest 是否自动加载 */
/** @var array $extraJs 额外的JS */
$context = $this->context;
$componentId = $context->id;
?>
<script>
    !function (global, top) { "use strict";
        global.ym2App.controller("ym2.ctrl.<?= $componentId ?>", [
            "$scope",
            "$http",
            "layui",
            "ymSpinner",
            "ym2",
            function ($scope, $http, layui, ymSpinner, ym2) {
                var componentId = "<?= $componentId ?>";
                var topToastr = top.toastr;
                var topSweetAlert = top.sweetAlert;
                var topLayer = top.layui.layer;
                var topJquery = top.jQuery;
                var topYmSpinner = top.ymSpinner;
                var tree = layui.tree;
                var dropdown = layui.dropdown;

                var httpSuccessCode = ym2.getHttpSuccessCode();
                var httpFailureCode = ym2.getHttpFailureCode();
                var httpUnauthorizedCode = ym2.getHttpUnauthorizedCode();
                var adminRouteLogin = ym2.getAdminRouteLogin();

                var MENU_ITEM = "MENU_ITEM";
                var menuItem;

                function setCache(key, value) { global.localStorage.setItem(key, value); }
                function getCache(key) { return global.localStorage.getItem(key); }
                function delCache(key) { global.localStorage.removeItem(key); }
                function clearCache() { global.localStorage.clear(); }
                function hasCache(key) { return !!getCache(key); }

                // 行事件选项
                var rowEventOptions = <?= Json::encode($rowEvents) ?>;
                var behaviorCall = <?= Json::encode($behaviorCall) ?>;

                //渲染菜单
                tree.render({
                    elem: "#" + componentId,
                    id: componentId,
                    data: [],
                    showLine: false, // 是否开启连接线
                    onlyIconControl: true, // 是否仅允许节点左侧图标控制展开收缩
                    text: {
                        defaultNodeName: "未命名", // 节点默认名称
                        none: "", // 数据为空时的提示文本
                    },
                    click: function(obj){
                        //加入缓存
                        setCache(MENU_ITEM, JSON.stringify(obj.data));
                        //调用其他组件
                        callOtherComp(obj.data);
                    },
                });
                //调用其他组件
                function callOtherComp(data) {
                    data = data || {};
                    var params;
                    var bre = global.ym2BehaviorReqExport;
                    for (var callId in behaviorCall) {
                        params = ym2.fillParams(behaviorCall[callId], data);
                        if (ym2.typeOf(bre[callId]) === "function") {
                            bre[callId].call(this, params);
                        }
                    }
                }
                //初始化方法
                $scope._initData = function () {
                    return new Promise(function (resolve, reject) {
                        $scope.loadingState = true;
                        $http.get("<?= $ajaxRoute ?>").then(function (result) {
                            $scope.loadingState = false;
                            var data = result.data;
                            resolve(data);
                            switch (data.code) {
                                case httpSuccessCode:
                                    var list = data.data || [];
                                    //重载菜单
                                    tree.reload(componentId, {
                                        data: list,
                                    });
                                    //删除缓存
                                    !list.length && delCache(MENU_ITEM);
                                    //添加缓存
                                    if (list.length && !hasCache(MENU_ITEM)) {
                                        setCache(MENU_ITEM, JSON.stringify(list[0]));
                                    }
                                    //渲染下拉工具栏
                                    rowEventOptions.length && renderDropDown();
                                    //选中当前菜单项
                                    selectedThis();

                                    break;
                                case httpFailureCode:
                                    topToastr.error(data.msg);
                                    break;
                                case httpUnauthorizedCode:
                                    // 授权失效, 去登录
                                    ym2.swal.timer(
                                        topSweetAlert,
                                        data.msg,
                                        "自动跳转; <a href='" + adminRouteLogin + "' target='_top'>立即跳转<a/>",
                                        function () {
                                            top.open(adminRouteLogin, "_self");
                                        },
                                        3000
                                    );
                                    break;
                                default:
                                    topToastr.error(data.msg);
                            }

                        }, function (error) {
                            reject(error);
                            $scope.loadingState = false;
                            topToastr.error(error.data || "系统错误, 发起请求失败!");
                            global.console.error(error);
                        });
                    });
                };
<?php if ($autoRequest): //是否自动加载数据 ?>
                //初始化菜单和其他组件调用
                $scope._initData().then(function (result) {
                    var cacheData = getCache(MENU_ITEM);
                    if (cacheData) {
                        menuItem = JSON.parse(cacheData);
                        callOtherComp(menuItem);
                    }
                });
<?php else: ?>
                var isInitial = false;
                global.ym2BehaviorReqExport["<?= $componentId ?>"] = function () {
                    if (isInitial === false) {
                        //初始化菜单和其他组件调用
                        $scope._initData().then(function (result) {
                            var cacheData = getCache(MENU_ITEM);
                            if (cacheData) {
                                menuItem = JSON.parse(cacheData);
                                callOtherComp(menuItem);
                            }
                        });

                        isInitial = true;
                    }
                };
<?php endif; ?>

                //菜单右键工具
                function renderDropDown() {
                    dropdown.render({
                        elem: "#" + componentId + " .layui-tree-entry",
                        trigger: "contextmenu",//右键点击
                        templet: '<span class="d-flex align-items-center"><i class="{{= d.icon }} f17"></i>&nbsp;{{= d.title }}</span>',
                        style: "width:100px;border-radius:8px;",//定义宽度，默认自适应
                        data: rowEventOptions,
                        click: function(obj, othis){
                            //当前数据ID
                            var dataID = this.elem.parent().data("id");
                            switch (obj.type) {
                                case "modal"://Modal
                                    $scope._actionModal(dataID, obj);
                                    break;
                                case "ajax"://AJAX
                                    $scope._actionAjax(dataID, obj);
                                    break;
                            }
                        }
                    });
                }
                //行Ajax
                $scope._actionAjax = function (dataID, config) {
                    ym2.swal.question(topSweetAlert, config.questionTitle, config.questionDescription, function (result) {
                        /* Read more about isConfirmed, isDenied below */
                        if (result.isConfirmed) {
                            // 发起ajax
                            // show loading
                            var $instance, flag = ymSpinner.show();
                            if (config.method === "GET") {
                                $instance = $http.get(
                                    ym2.addUrlQueryParam(config.route, {
                                        id: dataID,
                                    })
                                );
                            } else {
                                $instance = $http.post(config.route, { id: dataID });
                            }
                            $instance.then(function (result) {
                                ymSpinner.hide(flag);

                                var data = result.data;
                                switch (data.code) {
                                    case httpSuccessCode:
                                        ym2.swal.ok(topSweetAlert, data.msg);
                                        //初始化菜单数据
                                        $scope._initData();
                                        break;
                                    case httpFailureCode:
                                        topToastr.error(data.msg);
                                        break;
                                    case httpUnauthorizedCode:
                                        // 授权失效, 去登录
                                        ym2.swal.timer(
                                            topSweetAlert,
                                            data.msg,
                                            "自动跳转; <a href='" + adminRouteLogin + "' target='_top'>立即跳转<a/>",
                                            function () {
                                                top.open(adminRouteLogin, "_self");
                                            },
                                            3000
                                        );
                                        break;
                                    default:
                                        topToastr.error(data.msg);
                                }
                            }, function (error) {
                                ymSpinner.hide(flag);
                                ym2.swal.fail(topSweetAlert, error.data || "系统错误,发起请求失败!");
                                global.console.error(error);
                            });
                        }
                    });
                };
                //行Modal
                $scope._actionModal = function (dataID, config) {
                    var url = ym2.addUrlQueryParam(config.route, {
                        id: dataID,
                    });
                    var layerScreenObj = ym2.layerScreenOptions(config.width);
                    var refererName = ym2.layerRefererWindowName( config.refererWindow );
                    // iframe 模态框
                    // var loadingFlag = topYmSpinner.show("加载中...");
                    var layerCf = {
                        type: 2, // iframe
                        //skin: 'layui-layer-win10',
                        area: [layerScreenObj.width, config.height],
                        title: config.modalTitle,
                        shade: 0.3, // 遮罩透明度
                        shadeClose: false, // 点击遮罩区域，关闭弹层
                        closeBtn: config.titleCloseBtn,
                        maxmin: config.titleMaxminBtn, // 允许全屏最小化
                        anim: 0, // 0-6 的动画形式，-1 不开启
                        scrollbar: false, // 打开弹层时，是否允许浏览器出现滚动条。
                        content: url,
                        success: function(layero, index, that){
                            // topYmSpinner.hide( loadingFlag );
                            // 弹层的最外层元素的 jQuery 对象
                            //console.log(layero);
                            // 弹层的索引值
                            //console.log(index);
                            // 弹层内部原型链中的 this --- 2.8+
                            //console.log(that);
                            // 获取iframe的窗口对象, 添加来源追踪
                            var iframeWin = top[layero.find("iframe")[0]["name"]];
                            iframeWin.__REFERER_WIN_NAME = refererName;
                        },
                    };

                    topLayer.open(layerCf);
                };
                //UI脚本
                var jQueryElement = $("#" + componentId);
                jQueryElement.on("click", ".layui-tree-txt", function (e) {
                    jQueryElement.find(".layui-tree-entry").removeClass("menu-active-this");
                    $(this).closest(".layui-tree-entry").addClass("menu-active-this");
                }).on("click", ".layui-tree-iconClick", function (e) {
                    e.stopPropagation();
                });
                function selectedThis() {
                    var cacheData = getCache(MENU_ITEM);
                    if (cacheData) {
                        menuItem = JSON.parse(cacheData);
                        jQueryElement.find('[data-id="' + menuItem.id + '"]').children(".layui-tree-entry").addClass("menu-active-this");
                    }
                }
                // 工具栏事件
                $scope.toolbarAction = function (options) {
                    switch (options.type) {
                        case "modal":
                            $scope._actionToolbarModal(options);
                            break;
                    }
                };
                // 工具栏 - modal
                $scope._actionToolbarModal = function (config) {
                    // layer动态唯一索引
                    var activeIndex = topLayer.index;
                    var layerScreenObj = ym2.layerScreenOptions(config.width);
                    var refererName = ym2.layerRefererWindowName( config.refererWindow );
                    // iframe 模态框
                    // var loadingFlag = topYmSpinner.show("加载中...");
                    var layerCf = {
                        type: 2, // iframe
                        //skin: 'layui-layer-win10',
                        area: [layerScreenObj.width, config.height],
                        title: config.modalTitle || "&emsp;",
                        shade: 0.3, // 遮罩透明度
                        shadeClose: false, // 点击遮罩区域，关闭弹层
                        closeBtn: config.titleCloseBtn,
                        maxmin: config.titleMaxminBtn, // 允许全屏最小化
                        anim: 0, // 0-6 的动画形式，-1 不开启
                        scrollbar: false, // 打开弹层时，是否允许浏览器出现滚动条。
                        content: config.route,
                        success: function(layero, index, that){
                            // topYmSpinner.hide( loadingFlag );
                            // 弹层的最外层元素的 jQuery 对象
                            //console.log(layero);
                            // 弹层的索引值
                            //console.log(index);
                            // 弹层内部原型链中的 this --- 2.8+
                            //console.log(that);
                            // 获取iframe的窗口对象, 添加来源追踪
                            var iframeWin = top[layero.find("iframe")[0]["name"]];
                            iframeWin.__REFERER_WIN_NAME = refererName;
                            //键盘事件关闭
                            topJquery(".ym2_kc_" + activeIndex).focus().on("keydown", function (e) {
                                // 空格和回车键
                                if (e.keyCode === 13 || e.keyCode === 32) {
                                    topJquery(this).trigger("click");
                                }
                            });
                        },
                    };

                    if (config.closeBtn) {
                        layerCf.btn = ['<span class="ym2_keydown_close ym2_kc_' + activeIndex + '" tabindex="0">关闭</span>'];
                    }

                    topLayer.open(layerCf);
                };
                // 暴露给window，用于回调刷新
                global.ym2CbkExport[componentId] = $scope._initData;
                //额外的JS脚本
                <?= !empty($extraJs) ? implode("\n", $extraJs) : '' ?>

            },
        ]);
    }(window, top);
</script>
